<?php
/**
 * QrcodeService
 *
 *
 * @return
 * @author ninetyseven.
 * @date 2023/4/29
 */

namespace App\Services;

use App\Enum\CodeEnum;
use Illuminate\Support\Facades\Log;
use OSS\Core\OssException;
use OSS\OssClient;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class QrcodeService extends BaseService
{

    /**
     * 生成二维码
     * getQrcode
     * @param string $url
     * @param string $fileName
     * @param string $menu
     * @param int $size
     * @param string $ext
     * @return mixed
     * @throws OssException
     * @author ninetyseven.
     * @date 2023/4/29
     */
    public static function getQrcode(string $url = '',string $fileName = '', string $menu = 'code', int $size = 200, string $ext = 'png')
    {
        $basePath = public_path();
        $path = $menu . '/' . date('Ymd') . '/';

        $fileName = $path . sha1($url) .'-'.$fileName. '.' . $ext;
        if (!is_dir($basePath.'/'.$path)) {
            mkdir($basePath.'/'.$path, 0777, true);
        }

        $link = public_path($fileName);
        QrCode::format($ext)->size($size)->margin(1)->generate($url, $link);

        $KeyId = env('ACCESS_KEY_ID');
        $KeySecret = env('ACCESS_KEY_SECRET');
        $EndPoint = env('OSS_URL');
        $Bucket = env('BUCKET');
        $s = 'generate qrcode. config from env: keyId=%s，keySecret=%s,endpoint=%s, bucket=%s';
        Log::debug(sprintf($s,$KeyId,$KeySecret,$EndPoint,$Bucket));

        $options = [
            OssClient::OSS_HEADERS => [
                'Content-Type' => 'image/jpg',
            ],
        ];

        $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint,true);

        $result = $ossClient->uploadFile($Bucket, $fileName, $link, $options);

        //上传失败
        if (!$result) {
            throw new \Exception('上传失败');
        }

        //清理本地文件
        if (is_link($link)) {
            $file = readlink($link);
            unlink($link);
            if ($file && is_file($file)) {
                unlink($file);
            }
        }

        return $result['info']['url'];
    }
}
